package base

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type LocalTime time.Time

const TimeFormat = "2006-01-02 15:04:05"

func (t *LocalTime) MarshalJSON() ([]byte, error) {
	if time.Time(*t).IsZero() {
		return []byte("\"\""), nil
	}
	b := make([]byte, 0, len(TimeFormat)+2)
	b = append(b, '"')
	b = time.Time(*t).AppendFormat(b, TimeFormat)
	b = append(b, '"')
	return b, nil
}
func (t *LocalTime) UnmarshalJSON(data []byte) error {
	if len(data) > 2 && data[0] == '"' {
		now, err := time.ParseInLocation(`"`+TimeFormat+`"`, string(data), time.Local)
		*t = LocalTime(now)
		return err
	}
	return nil
}
func (t LocalTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	tlt := time.Time(t)
	//判断给定时间是否和默认零时间的时间戳相同
	if tlt.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return tlt.Format("2006-01-02 15:04:05.000"), nil
}
func (t *LocalTime) Scan(v interface{}) error {
	if value, ok := v.(time.Time); ok {
		*t = LocalTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
func (t *LocalTime) String() string {
	tTime := time.Time(*t)
	return tTime.Format("2006-01-02 15:04:05.000")
}
